﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;

namespace DataChangeTools.Extensions
{
    public static class WatermarkHelper
    {
        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.RegisterAttached(
                "Watermark",
                typeof(string),
                typeof(WatermarkHelper),
                new PropertyMetadata("请输入内容", OnWatermarkChanged));

        public static string GetWatermark(DependencyObject obj) => (string)obj.GetValue(WatermarkProperty);
        public static void SetWatermark(DependencyObject obj, string value) => obj.SetValue(WatermarkProperty, value);

        private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is System.Windows.Controls.TextBox textBox)
            {
                textBox.Loaded += (s, args) => UpdateWatermark(textBox);
                textBox.TextChanged += (s, args) => UpdateWatermark(textBox);
            }
        }

        private static void UpdateWatermark(System.Windows.Controls.TextBox textBox)
        {
            var watermark = GetWatermark(textBox);
            var textBlock = textBox.Template.FindName("watermark", textBox) as TextBlock;
            if (textBlock != null)
            {
                textBlock.Text = watermark;
                textBlock.Visibility = string.IsNullOrEmpty(textBox.Text)
                    ? Visibility.Visible
                    : Visibility.Collapsed;
            }
        }
    }
}
